from absl import app, flags
import datetime

import coin.base.database.util as db_util
import coin.support.accounting.logic.account_status_util as account_status
from coin.support.accounting.logic.mysql_importer import \
  MysqlAccountInfoImporter as MysqlImporter
from xunkemgmt.support.accounting.logic.query_request import get_fill_collector_request, filter_invalid_request_and_result
from xunkemgmt.strategy.analytics.views.util.query_util import fetch_pta

FLAGS = flags.FLAGS

def gen_fill_collecter_params_from_pta(trading_date):
  all_trading_symbols = fetch_pta(trading_date,
                                  trading_date,
                                  business_unit='coin',
                                  fetch_cols=['market_type', 'exchange', 'owner', 'symbol'],
                                  pta_type='SYMBOL')
  all_trading_symbols = all_trading_symbols.dropna().drop_duplicates()
  fill_request_list = get_fill_collector_request(trading_date, all_trading_symbols)
  product_str_list = all_trading_symbols['symbol'].tolist()
  assert len(fill_request_list) == len(product_str_list)
  filter_fill_request_list = []
  filter_product_str_list = []
  for request, product_str in zip(fill_request_list, product_str_list):
    if request is None:
      continue
    if FLAGS.market_type and request.market_type not in FLAGS.market_type:
      request = None
    elif FLAGS.exchange and request.exchange not in FLAGS.exchange:
      request = None
    elif FLAGS.owner and request.owner not in FLAGS.owner:
      request = None
    if request:
      filter_fill_request_list.append(request)
      filter_product_str_list.append(product_str)
  return filter_fill_request_list, filter_product_str_list

def collect_fills(request_list, product_str_list, trading_date):
  start_time = datetime.datetime.combine(trading_date, datetime.time.min)
  end_time = datetime.datetime.combine(trading_date, datetime.time.max)
  response_list = account_status.query_history_fills_list(request_list, product_str_list, start_time, end_time)
  request_list, response_list = filter_invalid_request_and_result(request_list, response_list)
  db_config = db_util.read_db_config(FLAGS.mysql_config)
  importer = MysqlImporter(db_config=db_config)
  importer.insert_fill_history(request_list, response_list)


def main(_):
  max_date = datetime.datetime.utcnow().date() - datetime.timedelta(days=1)
  if FLAGS.start_date is None and FLAGS.end_date is None:
    start_date = max_date
    end_date = start_date
  else:
    start_date = datetime.datetime.strptime(FLAGS.start_date, '%Y%m%d').date()
    end_date = datetime.datetime.strptime(FLAGS.end_date, '%Y%m%d').date()
  assert start_date <= end_date <= max_date, (start_date, end_date, max_date)
  trading_date = end_date
  while trading_date >= start_date:
    fill_request_list, product_str_list = gen_fill_collecter_params_from_pta(trading_date)
    collect_fills(fill_request_list, product_str_list, trading_date)
    trading_date -= datetime.timedelta(1)


if __name__ == '__main__':
  flags.DEFINE_string('start_date', None, '%Y%m%d')
  flags.DEFINE_string('end_date', None, '%Y%m%d')
  flags.DEFINE_string('market_type', None, 'market_type')
  flags.DEFINE_string('exchange', None, 'exchange')
  flags.DEFINE_string('owner', None, 'owner')
  flags.DEFINE_string(
    'mysql_config',
    "../../coin_deploy/support_accounting/db_config/mysql_config_prod.json",
    'path of database config.'
  )
  app.run(main)
